package com.dfhc.bus.workmanger;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.RepositoryService;
import org.quickbundle.project.RmGlobalReference;
import org.quickbundle.project.RmProjectHelper;
import org.quickbundle.project.common.vo.RmCommonVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dfhc.ISystemConstant;
import com.dfhc.rm.user.service.UserService;
import com.dfhc.rm.user.vo.UserVo;
import com.dfhc.util.StringHelper;

/**
 * 前台工作管理->我的工作处理
 */
@Controller
@RequestMapping(value = "/workprocess")
public class WorkProcessController implements  IWorkProcessConstants {
	@Autowired
	private UserService userService;
	@Autowired
	private RepositoryService repositoryService;
	
	
	  @RequestMapping(value = "workShow"+ISystemConstant.SUFFIX_ACTION)
	    public String listL(Model model, HttpServletRequest request) throws UnsupportedEncodingException {
	    	//头类型
	    	String   titleType=request.getParameter(TITLE_TYPE);
	    	if(StringHelper.isEmpty(titleType)){
	    		titleType=TITLE_TYPE_MY_WORK;
	    	}
//	    	if(TITLE_TYPE_LIST_HISTORY.equals(titleType)){
//	    		//流程模型
//	    		listHistory(request,model);
//	    	}
	    	if(TITLE_TYPE_MY_WORK.equals(titleType)){
	    		//流程定义
	    		myWork(request,model);
	    	}
	    	model.addAttribute(TITLE_TYPE, titleType);
	    	return "/qb5activiti/bus/workmanger/show";
	    }
	  /** 我的工作流查询 
		 * 工作流程查询
		 * @param request
		 * @param model
		 * @return
	 * @throws UnsupportedEncodingException 
		 */
		public void myWork(HttpServletRequest request, Model model) throws UnsupportedEncodingException{
			String procName2 = request.getParameter("procName");//流程定义名称
			if(!StringHelper.isEmpty(procName2)){
		    	String paramsTrans = new String(procName2.getBytes("ISO-8859-1"),"UTF-8");
		    	procName2 = java.net.URLDecoder.decode(paramsTrans, "UTF-8");
		        model.addAttribute("procName", procName2);
	        }
			String startSign = request.getParameter("startSign");//发起时间比较标志
			if(!StringHelper.isEmpty(startSign)){
		    	String startSign2 = new String(startSign.getBytes("ISO-8859-1"),"UTF-8");
		    	startSign = java.net.URLDecoder.decode(startSign2, "UTF-8");
		        model.addAttribute("startSign", startSign);
	        }
			String workdays = request.getParameter("workdays");//工作日
			model.addAttribute("workdays", workdays);
			String userId = RmProjectHelper.getRmUserId(request);
			int startPageNum = 1;
			if(!StringHelper.isEmpty(request.getParameter("page"))){
				startPageNum = Integer.valueOf(request.getParameter("page"));
			}
			
			String sqlString2 = "SELECT * FROM (SELECT WK_PRO.ID AS id, WK_PRO.PROC_DEF_ID AS procDefId, WK_PRO.PROC_KEY AS procKey, WK_PRO.PROC_INST_ID AS procInstId, WK_PRO.PROC_NAME AS procName, WK_PRO.BUSINESS_ATTRIBUTE4 AS procTitle, WK_PRO.INITIATOR_ID AS startUserId, WK_PRO.INITIATOR AS startUserName, WK_PRO.INITIATOR_TIME AS startTime, WK_PRO.BUSINESS_ATTRIBUTE2 AS ranking FROM WK_GENERAL_BUSINESS_PROCESS WK_PRO WHERE WK_PRO.INITIATOR_ID = '"+userId+"' AND WK_PRO.INITIATOR IS NOT NULL)a WHERE startUserId='"+userId+"'";
			String sqlCount2=this.addSqlConditString(sqlString2, procName2, startSign, workdays,true);
			sqlString2 = this.addSqlConditString(sqlString2, procName2, startSign, workdays,false);
			
			
			String sqlList2 = sqlString2 + " order by id desc LIMIT "+(startPageNum-1)*10+",10";
			
			List<RmCommonVo> taskCounts = RmProjectHelper.getCommonServiceInstance().doQuery(sqlCount2);
			
			String recordNum = taskCounts.get(0).getString("countNum");
			List<RmCommonVo> taskList = RmProjectHelper.getCommonServiceInstance().doQuery(sqlList2);
			
			
			//查询所有的流程模型
			List<org.activiti.engine.repository.Model> modelList = repositoryService.createModelQuery().list();

			//查询所有的用户
			Map<String, Object> searchPara = new HashMap<String, Object>();
			 if(!StringHelper.isEmpty(procName2)){
		        	searchPara.put("procName2", procName2);
		        	
				}
		    searchPara.put("usableStatus", ISystemConstant.DICTIONARY_RM_YES_NOT_1);
		    
		    List<UserVo> userVos = userService.list(searchPara, null);  //按条件查询全部,带排序
		    Map<String,Object> levels= RmGlobalReference.get(ISystemConstant.DEFAULT_LEVEL);//查询任务级别
		    model.addAttribute("levels", levels);
		    model.addAttribute("userVos", userVos);
			model.addAttribute("modelList", modelList);
			model.addAttribute("taskVos", taskList);
			model.addAttribute("procName", procName2);
			model.addAttribute("recordNum", recordNum);
			model.addAttribute("currentPage", startPageNum);
		}
		
		/**
		 * 给sql语句根据条件添加条件
		 * @param sqlString 原sql语句
		 * @param procName 流程名称
		 * @param startSign 日期比较格式
		 * @param workdays 工作日天数
		 * @param startUserName 发起人
		 * @return 新sql语句
		 */
		public String addSqlConditString(String sqlString2, String procName2, String startSign, String workdays,boolean isCount){
			
			if(isCount){
				sqlString2 = sqlString2.replace("SELECT * FROM", "SELECT count(*) as countNum FROM ");
			}
			if(!StringHelper.isEmpty(procName2)){
				sqlString2 += " AND procTitle like '%"+procName2+"%'";
			}
			if(!StringHelper.isEmpty(startSign) && !StringHelper.isEmpty(workdays)){
				if("大于或等于".equals(startSign)){
					sqlString2 += "AND TO_DAYS(NOW()) - TO_DAYS(startTime) >= "+workdays;
				}else if("小于".equals(startSign)){
					sqlString2 += "AND TO_DAYS(NOW()) - TO_DAYS(startTime) < "+workdays;
				}else if("大于".equals(startSign)){
					sqlString2 += "AND TO_DAYS(NOW()) - TO_DAYS(startTime) > "+workdays;
				}else if("小于或等于".equals(startSign)){
					sqlString2 += "AND TO_DAYS(NOW()) - TO_DAYS(startTime) <= "+workdays;
				}
			}
			/*if(!StringHelper.isEmpty(startUserName)){
				String[] userNameArr = startUserName.split(",");
				sqlString2 += " AND (";
				String userSql = "";
				for (String userName : userNameArr) {
					if(StringHelper.isEmpty(userSql)){
						userSql += "UM.NAME LIKE '%"+userName+"%'";
					}else{
						userSql += "OR UM.NAME LIKE '%"+userName+"%'";
					}
				}
				sqlString2 += userSql + ")";
			}*/
			return sqlString2;
		}
	/**
	 * 给sql语句根据条件添加条件
	 * @param sqlString 原sql语句
	 * @param procName 流程名称
	 * @param startSign 日期比较格式
	 * @param workdays 工作日天数
	 * @param startUserName 发起人
	 * @return 新sql语句
	 */
	public String addSqlCondit(String sqlString, String procName, String startSign, String workdays, String startUserName){
		if(!StringHelper.isEmpty(procName)){
			sqlString += " AND PRO.BUSINESS_ATTRIBUTE4 like '%"+procName+"%'";
		}
		if(!StringHelper.isEmpty(startSign) && !StringHelper.isEmpty(workdays)){
			if("大于或等于".equals(startSign)){
				sqlString += "AND TO_DAYS(NOW()) - TO_DAYS(TSK.START_TIME_) >= "+workdays;
			}else if("小于".equals(startSign)){
				sqlString += "AND TO_DAYS(NOW()) - TO_DAYS(TSK.START_TIME_) < "+workdays;
			}else if("大于".equals(startSign)){
				sqlString += "AND TO_DAYS(NOW()) - TO_DAYS(TSK.START_TIME_) > "+workdays;
			}else if("小于或等于".equals(startSign)){
				sqlString += "AND TO_DAYS(NOW()) - TO_DAYS(TSK.START_TIME_) <= "+workdays;
			}
		}
		if(!StringHelper.isEmpty(startUserName)){
			String[] userNameArr = startUserName.split(",");
			sqlString += " AND (";
			String userSql = "";
			for (String userName : userNameArr) {
				if(StringHelper.isEmpty(userSql)){
					userSql += "UM.NAME LIKE '%"+userName+"%'";
				}else{
					userSql += "OR UM.NAME LIKE '%"+userName+"%'";
				}
			}
			sqlString += userSql + ")";
		}
		return sqlString;
	}
	

		
}
